package com.cdtye.itps.cms.service.datasysn;

import com.cdtye.common.kafkacore.dao.KfkConsumerErrorDao;
import com.cdtye.common.kafkacore.model.attr.ConsumerErrorAttr;
import com.cdtye.common.kafkacore.model.entity.KfkConsumerError;
import com.cdtye.common.kafkacore.service.KfkConsumerErrorService;
import com.cdtye.common.webcore.util.DateUtil;
import com.cdtye.itps.cms.dao.defect.entity.JcwDefectInfoPhoto;
import com.cdtye.itps.cms.dao.defect.entity.JcwProblemDefectCategory;
import com.cdtye.itps.cms.dao.defect.entity.JcwProblemDefectInfo;
import com.cdtye.itps.cms.dao.defect.entity.JcwProblemDefectLevel;
import com.cdtye.itps.cms.dao.detect.*;
import com.cdtye.itps.cms.dao.pillar.entity.JcwPillar;
import com.cdtye.itps.cms.service.defect.JcwDefectInfoPhotoService;
import com.cdtye.itps.cms.service.defect.JcwProblemDefectCategoryService;
import com.cdtye.itps.cms.service.defect.JcwProblemDefectInfoService;
import com.cdtye.itps.cms.service.defect.JcwProblemDefectLevelService;
import com.cdtye.itps.cms.service.pillar.JcwPillarService;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class PlanDetailTmisService {

    @Autowired
    private JcwProblemDefectInfoService jcwProblemDefectInfoService;

    @Autowired
    private JcwDefectInfoPhotoService jcwDefectInfoPhotoService;

    @Autowired
    private JcjcHandleTmisService jcjcHandleTmisService;

    @Autowired
    private JcwProblemDefectCategoryService jcwProblemDefectCategoryService;

    @Autowired
    private JcwProblemDefectLevelService jcwProblemDefectLevelService;

    @Autowired
    private KfkConsumerErrorService kfkConsumerErrorService;

    @Autowired
    private KfkConsumerErrorDao kfkConsumerErrorDao;

    @Autowired
    private JcjcHandleService jcjcHandleService;

    @Autowired
    private JcwPillarService jcwPillarService;


    @Async
    public void handleDefectSection(List<JcwProblemDefectInfo> dtoList, String updateBy) {

        //获取基础数据进行验证
        XxlJobLogger.log("Tmis开始预处理[6C-检测缺陷]----------");
        log.info("Tmis开始预处理[6C-检测缺陷]----------");

        if (CollectionUtils.isEmpty(dtoList)) {
            return;
        }

        //查询所有缺陷分类
        Map<String, JcjcDefectTypeSection> defectTypeMap = jcjcHandleTmisService.findDefectTypesMapSection(null, "4226");

        //查询所有缺陷等级
        Map<String, JcjcDefectGradeSection> defectGradeMap = jcjcHandleTmisService.findDefectGradesMapSection(null);

        //查询所有缺陷来源
        JcjcDefectSourceTypeSection JcjcDefectSourceTypeSection = jcjcHandleTmisService.findDefectSourceTypeId();

        for (JcwProblemDefectInfo dto : dtoList) {
            //段级对象
            JcjcDefectInfoSection jcjcDefectInfoSection = dto.covEntity();
            //把所有属性标准化，attr或list需要手动转换
            List<ConsumerErrorAttr> errorList = new ArrayList<>();
            //1、处理部门
            jcjcDefectInfoSection.setDeptId(dto.getFindDeptId());
            jcjcDefectInfoSection.setFindDeptId(dto.getFindDeptId());
            //2、处理线路
            jcjcDefectInfoSection.setSeclineId(dto.getLineId());
            //3、处理区站
            jcjcDefectInfoSection.setSiteId(dto.getLineSiteId());
            //4、处理行别
            jcjcDefectInfoSection.setDirectionId(dto.getDirectionId());
            //5、处理隧道
            jcjcDefectInfoSection.setTunnelId(dto.getTunnelId());
            //6、处理支柱
            jcjcDefectInfoSection.setPillarId(dto.getPillarId());
            jcjcDefectInfoSection.setRoadMark(dto.getRoadMark());
            jcjcDefectInfoSection.setPillarNum(dto.getPillarNum());
            jcjcDefectInfoSection.setPillarDeptId(dto.getPillarDeptId());


            //7、处理缺陷分类
            if (StringUtils.isNotBlank(dto.getDefectCategoryId())) {
                JcwProblemDefectCategory jcwProblemDefectCategory = jcwProblemDefectCategoryService.getJcwProblemDefectCategoryById(dto.getDefectCategoryId());
                JcjcDefectTypeSection jcjcDefectTypeSection = defectTypeMap.get(jcwProblemDefectCategory.getCategoryName());
                if (jcjcDefectTypeSection == null) {
                    errorList.add(jcjcHandleService.getUserDefectTypeErrorAttr(jcwProblemDefectCategory.getCategoryName(), "--用户缺陷分类不存在"));
                } else {
                    jcjcDefectInfoSection.setDefectTypeId(jcjcDefectTypeSection.getDefectTypeId());
                }
            }

            //8、处理缺陷等级
            if (StringUtils.isNotBlank(dto.getDefectLevelId())) {
                JcwProblemDefectLevel jcwProblemDefectLevel = jcwProblemDefectLevelService.getJcwProblemDefectLevelById(dto.getDefectLevelId());
                JcjcDefectGradeSection jcjcDefectGradeSection = defectGradeMap.get(jcwProblemDefectLevel.getLevelName().replace("类", ""));
                if (jcjcDefectGradeSection == null) {
                    errorList.add(jcjcHandleService.getUserDefectGradeErrorAttr(jcwProblemDefectLevel.getLevelName(), "--缺陷等级不存在"));
                } else {
                    jcjcDefectInfoSection.setDefectGradeId(jcjcDefectGradeSection.getDefectGradeId());
                }
            }

            //9、处理缺陷成因
            //10、处理缺陷来源
            jcjcDefectInfoSection.setDiscoverSourceTypeId(JcjcDefectSourceTypeSection.getSourceTypeId());
            //11、处理缺陷部位
            //12、股道
//            JcwPillar jcwPillarBureau = jcwPillarService.getById(dto.getPillarId());
//            if (StringUtils.isNotBlank(jcwPillarBureau.getTrackId())) {
//                if (jcwPillarBureau.getTrackId().contains(",")) {//支柱有可能会跨多股道，导致插入缺陷表报错，这里取第一个
//                    String trackId = jcwPillarBureau.getTrackId().substring(0, jcwPillarBureau.getTrackId().indexOf(","));
//                    jcjcDefectInfoSection.setTrackId(trackId);
//                } else {
//                    jcjcDefectInfoSection.setTrackId(jcwPillarBureau.getTrackId());
//                }
//            }


            //判断预处理是否通过。通过：保存数据，不通过保存异常数据
            if (CollectionUtils.isEmpty(errorList)) {
                List<JcjcDefectInfoSection> list = jcjcHandleTmisService.selectIdTmisDefectInfo(jcjcDefectInfoSection);
                if (CollectionUtils.isEmpty(list)) {
                    //新增
                    jcjcDefectInfoSection.setCreateDatetime(DateUtil.getDateTime());
                    boolean b = jcjcHandleTmisService.insertTimsDefectInfo(jcjcDefectInfoSection);
                    if (b) {
                        //处理图片
                        List<JcwDefectInfoPhoto> picBureauList = jcwDefectInfoPhotoService.findByDefectInfoId(dto.getId());
                        if (!CollectionUtils.isEmpty(picBureauList)){
                            //defectInfoId fileName filePath
                            List<JcwDefectInfoPhoto> picSectionList = new ArrayList<>();
                            picBureauList.forEach(i->{
                                picSectionList.add(new JcwDefectInfoPhoto()
                                        .setDefectInfoId(jcjcDefectInfoSection.getDefectInfoId())
                                        .setFileName(i.getFileName())
                                        .setFilePath(i.getFilePath())
                                        .setPhotoFlag("3")
                                        .setFileType("1"));
                            });
                            jcjcHandleTmisService.insertDefectInfoPhoto(picSectionList);
                        }
                    }


                } else {//修改
                    JcjcDefectInfoSection jcjcDefectInfoSectionUpdate = list.get(0);
                    jcjcDefectInfoSection.setDefectInfoId(jcjcDefectInfoSectionUpdate.getDefectInfoId());
                    jcjcDefectInfoSection.setUpdateDatetime(DateUtil.getDateTime());
                    jcjcHandleTmisService.updateTmisDefectInfo(jcjcDefectInfoSection);

                }

                //修改局级缺陷 同步状态 --成功
                JcwProblemDefectInfo jcwProblemDefectInfoUpdate = new JcwProblemDefectInfo();
                jcwProblemDefectInfoUpdate.setId(dto.getId());
                jcwProblemDefectInfoUpdate.setSysnStatus("2");
                jcwProblemDefectInfoUpdate.setUpdateDatetime(DateUtil.getDateTime());
                jcwProblemDefectInfoUpdate.setUpdateBy(updateBy);
                jcwProblemDefectInfoService.updateById(jcwProblemDefectInfoUpdate);

            } else {
                Criteria criteria = Criteria.where("status").is(0);
                criteria.and("producerId").is(dto.getId());
                criteria.and("topic").regex("topic_itps_detect_section");
                KfkConsumerError error = kfkConsumerErrorDao.findOne(criteria);
                if (error == null) {
                    //保存预处理未通过
                    ConsumerRecord record = new ConsumerRecord("topic_itps_detect_section", 0, 0, "itps_defect_section", null);
                    KfkConsumerError errorModel = new KfkConsumerError(record, dto.getId(), dto.getId()).setErrorData(dto).setConsumerErrorList(errorList);
                    kfkConsumerErrorService.insert(errorModel);
                }

                //修改局级缺陷 同步状态 --失败
                JcwProblemDefectInfo jcwProblemDefectInfoUpdate = new JcwProblemDefectInfo();
                jcwProblemDefectInfoUpdate.setId(dto.getId());
                jcwProblemDefectInfoUpdate.setSysnStatus("1");
                jcwProblemDefectInfoUpdate.setUpdateDatetime(DateUtil.getDateTime());
                jcwProblemDefectInfoUpdate.setUpdateBy(updateBy);
                jcwProblemDefectInfoService.updateById(jcwProblemDefectInfoUpdate);

            }
        }
    }
}
